package com.zyh.servlet;

import com.zyh.core.AjaxResult;
import com.zyh.core.BaseHttpServlet;
import com.zyh.dao.impl.StudentDaoImpl;
import com.zyh.domain.Student;
import com.zyh.service.IStudentService;
import com.zyh.service.impl.StudentServiceImpl;
import com.zyh.utils.RequestUtils;
import com.zyh.utils.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/student/*")
public class StudentCRUDServlet extends BaseHttpServlet {
    private IStudentService studentService;

    @Override
    public void init() {
        studentService = new StudentServiceImpl(new StudentDaoImpl());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");

        // 获取参数
        if (!req.getParameterMap().containsKey("id")) {
//            // 提示前端缺少ID的参数
//            resp.setContentType("application/json;charset=utf-8");
//            // {"code":400,"msg":"请传入id字段"}
//            resp.getWriter().write("{\"code\":400,\"msg\":\"请传入id字段\"}");
            ResponseUtils.responseJson(resp, AjaxResult.error(400, "请传入id"));
            return;
        }
        int id = Integer.parseInt(req.getParameter("id"));

        // 用户传入了id
//        try {
//            Student student = studentService.getStudent(id);
//            // 正常返回数据
////            JSONObject jsonObject = new JSONObject();
////            jsonObject.put("code", 200);
////            jsonObject.put("msg", "请求成功");
////            jsonObject.put("data", student);
////            resp.setCharacterEncoding("utf-8");
////            resp.setContentType("application/json;charset=utf-8");
////            resp.getWriter().write(jsonObject.toJSONString());
//            ResponseUtils.responseJson(resp, AjaxResult.success(student));
//        } catch (SQLException e) {
//            e.printStackTrace();
//           ResponseUtils.responseJson(resp, AjaxResult.error());
//        }

        executeBusiness(resp, response -> {
            Student student = studentService.getStudent(id);
            ResponseUtils.responseJson(resp, AjaxResult.success(student));
        });

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        BufferedReader reader = req.getReader();
//        StringBuilder sb = new StringBuilder();
//        String line = null;
//        while ((line = reader.readLine()) != null) {
//            sb.append(line);
//        }
//        Student student = JSONObject.parseObject(sb.toString(), Student.class);

        String pathInfo = req.getPathInfo();
        if (pathInfo == null) {
            // 新增功能
            Student student = RequestUtils.getReqJsonBody(req, Student.class);

            // 执行业务逻辑
            executeBusiness(resp, response -> {
                ResponseUtils.responseJson(resp, AjaxResult.success(studentService.addStudent(student)));
            });
        } else if (pathInfo.equals("/list")) {
            Student student = RequestUtils.getReqJsonBody(req, Student.class);
            // pageNum, pageSize,total
            int pageNum = req.getParameter("pageNum") == null ? 1 : Integer.parseInt(req.getParameter("pageNum"));
            int pageSize = req.getParameter("pageSize") == null ? 10 : Integer.parseInt(req.getParameter("pageSize"));
            // 查询所有的列表
            executeBusiness(resp, response -> {
                ResponseUtils.responseJson(resp, AjaxResult.success(studentService.getStudentPage(pageNum,pageSize,student)));
            });
        }


    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (!req.getParameterMap().containsKey("id")) {
            ResponseUtils.responseJson(resp, AjaxResult.error(400, "请传入id"));
            return;
        }
        int id = Integer.parseInt(req.getParameter("id"));
        executeBusiness(resp, response -> {
            ResponseUtils.responseJson(resp, AjaxResult.success(studentService.deleteStudent(id)));
        });
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Student student = RequestUtils.getReqJsonBody(req, Student.class);
        if (student.getId() == null) {
            ResponseUtils.responseJson(resp, AjaxResult.error(400, "请传入id"));
            return;
        }

        // 执行业务逻辑
        executeBusiness(resp, response -> {
            ResponseUtils.responseJson(resp, AjaxResult.success(studentService.updateStudent(student)));
        });
    }
}
